package com.example.smartcity.fragment;

import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.smartcity.R;
import com.example.smartcity.activity.NewsWebViewActivity;
import com.example.smartcity.bean.NewsBean;
import com.example.smartcity.utils.APIConfig;
import com.google.gson.Gson;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


// 新闻类别：时政，电视，旅游，视频，广播，基层


public class NTVFragment extends BaseFragment {
    private static final String TAG = NTVFragment.class.getSimpleName();

    private ListView listView;
    private NewsBean newsBean;
    @Override
    public View initView() {
        Log.i(TAG, "电视的视图被实例化了");
        View view = View.inflate(getContext(), R.layout.news_tv, null);
        listView = view.findViewById(R.id.listView);
        getNewsData();


        return view;
    }



    @Override
    public void initData() {
        super.initData();
        Log.e(TAG, "电视的Fragment的数据被初始化了");
    }
    public void getNewsData(){
        Log.i("getNewsData"," Activated getNewsData");
        OkHttpClient client = new OkHttpClient();
        Request request  = new Request.Builder()
                .url(APIConfig.BASE_URL+"/news/findnewsbycategory?category=财经")
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i("onFailure",e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String result = response.body().string();
                    Log.i("News_Request_Success:",result);
                    Gson gson = new Gson();

                    newsBean = gson.fromJson(result, NewsBean.class);
                    //rowsBeans = gson.fromJson(newsBean.getRows(), listType);
                    Log.i("szrowsBeans",newsBean.getRows().toString());
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            NewsAdapter newsAdapter = new NewsAdapter();
                            listView.setAdapter(newsAdapter);
                            setListViewHeightBasedOnChildren(listView);
                            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                @Override
                                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                                    Intent intent = new Intent(getActivity(), NewsWebViewActivity.class);
                                    ImageView new_img = view.findViewById(R.id.new_img);
                                    new_img.setDrawingCacheEnabled(Boolean.TRUE);
                                    intent.putExtra("bitmap",new_img.getDrawingCache());
                                    intent.putExtra("title",newsBean.getRows().get(i).getTitle());
                                    intent.putExtra("time",newsBean.getRows().get(i).getCreateTime());
                                    intent.putExtra("content",newsBean.getRows().get(i).getContent());
                                   /* Bundle bundle = new Bundle();
                                    bundle.putString("img",newsBean.getRows().get(i).getImgUrl());
                                    bundle.putString("title",newsBean.getRows().get(i).getTitle());
                                    bundle.putString("content",newsBean.getRows().get(i).getContent());
                                    bundle.putString("time",newsBean.getRows().get(i).getContent());
                                    intent.putExtras(bundle);*/
                                    getActivity().startActivity(intent);
                                }
                            });

                        }
                    });
                }
            }
        });

    }
    public class NewsAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return newsBean!=null ? newsBean.getRows().size() : 0;
        }
        @Override
        public Object getItem(int i) {
            return newsBean.getRows().get(i);
        }
        @Override
        public long getItemId(int i) {
            return i;
        }
        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            NewsAdapter.ViewHolder holder;
            if (view==null) {
                view = View.inflate(getContext(), R.layout.news_item,null);
                holder = new NewsAdapter.ViewHolder();
                holder.new_title = view.findViewById(R.id.new_title);
                holder.new_context = view.findViewById(R.id.new_context);
                holder.new_create = view.findViewById(R.id.new_date);
                holder.viewsNumber = view.findViewById(R.id.viewsNumber);
                holder.new_img = view.findViewById(R.id.new_img);
                view.setTag(holder);
            } else {
                holder = (NewsAdapter.ViewHolder) view.getTag();
            }
            holder.viewsNumber.setText(newsBean.getRows().get(i).getViewsNumber()+"");
            holder.new_create.setText(newsBean.getRows().get(i).getCreateTime());
            holder.new_context.setText(newsBean.getRows().get(i).getContent());
            Log.i("szmsg",newsBean.getRows().get(i).getTitle());
            holder.new_title.setText(newsBean.getRows().get(i).getTitle());
            String url = APIConfig.BASE_URL+newsBean.getRows().get(i).getImgUrl();
            Glide.with(getActivity()).load(url).into(holder.new_img);
            return view;
        }
        class ViewHolder{
            TextView new_title;
            TextView new_context;
            TextView new_create;
            ImageView new_img;
            TextView viewsNumber;
        }
    }
    public static void setListViewHeightBasedOnChildren(ListView listView){
        NewsAdapter newsAdapter = (NewsAdapter) listView.getAdapter();
        if (newsAdapter==null){
            return;
        }
        int totalHeight=0;
        // newsAdapter.getCount() 获取返回数据项的数目
        for (int i=0;newsAdapter.getCount()>i;i++){
            View listItem = newsAdapter.getView(i,null,listView);
            // 计算子项View的宽高
            listItem.measure(0,0);
            // 统计所有子项的总高度
            totalHeight+=listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight+(listView.getDividerHeight()*(newsAdapter.getCount()-1));
        //getDividerHeight()：获取子项间分隔符占用的高度， params.height 得到整个ListView 完整显示需要的高度
        listView.setLayoutParams(params);
    }





}
